package com.sokal.easycare.modules.order.web;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sokal.easycare.modules.order.entity.withdraw.UserWithdraw;
import com.sokal.easycare.modules.order.entity.withdraw.WithdrawQuery;
import com.sokal.easycare.modules.order.service.WithdrawService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sokal.easycare.common.config.Global;
import com.sokal.easycare.common.persistence.Page;
import com.sokal.easycare.common.utils.StringUtils;
import com.sokal.easycare.common.web.BaseController;
import com.sokal.easycare.enums.OrderEnums;
import com.sokal.easycare.modules.order.dao.track.OmOrderTrackDao;
import com.sokal.easycare.modules.order.entity.UserOrder;
import com.sokal.easycare.modules.order.entity.track.OmOrderTrack;
import com.sokal.easycare.modules.order.pojo.OrderPojo;
import com.sokal.easycare.modules.order.service.UserOrderService;
import com.sokal.easycare.modules.sys.entity.MainUser;
import com.sokal.easycare.modules.sys.utils.UserUtils;

/**
 * 订单相关Controller
 * 
 * @author nibo
 * @version 2017-04-01
 */
@Controller
@RequestMapping(value = "${adminPath}/order/userOrder")
public class UserOrderController extends BaseController {

	@Autowired
	private UserOrderService userOrderService;
	@Autowired
	OmOrderTrackDao omOrderTrackDao;
	@Autowired
	private WithdrawService withdrawService;

	@ModelAttribute
	public OrderPojo get(@RequestParam(required = false) String id) {
		OrderPojo entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = userOrderService.getOrderPojo(id);
		}
		if (entity == null) {
			entity = new OrderPojo();
		}
		return entity;
	}

	@RequiresPermissions("order:userOrder:view")
	@RequestMapping(value = { "list", "" })
	public String list(UserOrder userOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<UserOrder> page = userOrderService.findPage(new Page<UserOrder>(request, response), userOrder);
		model.addAttribute("page", page);
		return "modules/order/userOrderList";
	}

	@RequiresPermissions("order:userOrder:view")
	@RequestMapping(value = "form")
	public String form(UserOrder userOrder, Model model) {
		model.addAttribute("userOrder", userOrder);
		return "modules/order/userOrderForm";
	}

	@RequiresPermissions("order:userOrder:edit")
	@RequestMapping(value = "save")
	public String save(UserOrder userOrder, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, userOrder)) {
			return form(userOrder, model);
		}
		// OmOrderTrack a=userOrder.getOmOrderTrack();
		// userOrderService.updateOmOrderTrack(userOrder.getOrderCode(),
		// userOrder.getOmOrderTrack().getTrackStaffName());
		// OmOrderTrack b=model.;
		userOrderService.save(userOrder);
		addMessage(redirectAttributes, "保存订单成功");
		return "redirect:" + Global.getAdminPath() + "/order/userOrder/?repage";
	}

	@RequiresPermissions("order:userOrder:edit")
	@RequestMapping(value = "delete")
	public String delete(UserOrder userOrder, RedirectAttributes redirectAttributes) {
		userOrderService.delete(userOrder);
		addMessage(redirectAttributes, "删除订单成功");
		return "redirect:" + Global.getAdminPath() + "/order/userOrder/?repage";
	}

	@RequiresPermissions("order:userOrder:edit")
	@RequestMapping(value = "change")
	@ResponseBody
	public String change(String orderCode, String itemId, String type, String loginName,
			String trackStaffUserLoginName) {
		if(StringUtils.isEmpty(loginName)){
			loginName="";
		}
		loginName=loginName.trim();
		MainUser mainUser = UserUtils.getByLoginName(loginName);
		if (StringUtils.isEmpty(itemId) && "1".equals(type.trim())) {
			userOrderService.crearOrderTrack(loginName, orderCode, null, OrderEnums.WorkOrderTypeEnum.sale.value(),
					OrderEnums.SaleWorkOrderStatusEnum.wait_offer.value(), null);
			return "修改成功";
		}
		UserOrder order = new UserOrder();
		order.setOrderCode(orderCode);
		order = userOrderService.get(order);
		if (order == null) {
			return "订单不存在";
		}
		if (StringUtils.isEmpty(itemId) && "3".equals(type.trim())) {
			order.setWarrantyTime(Integer.parseInt(loginName));
			userOrderService.updateOrder(order);
			return "修改成功";
		}
		if ("4".equals(type.trim())) {
			return userOrderService.changServerWork(order, loginName);
		}
		OmOrderTrack omOrderTrack = omOrderTrackDao.get(itemId);
		if (omOrderTrack == null) {
			return "修改失败";
		}

		if ("2".equals(type.trim())) {
			if (mainUser != null) {
				omOrderTrack.setSupervisorId(mainUser.getId());
			}
			if (StringUtils.isNotEmpty(trackStaffUserLoginName)) {
				MainUser trackStaffUser = UserUtils.getByLoginName(trackStaffUserLoginName);
				if (trackStaffUser == null) {
					return "修改失败:用户不存在" + trackStaffUserLoginName;
				}
				omOrderTrack.setTrackStaffId(trackStaffUser.getId());
			}
			if (mainUser == null && StringUtils.isEmpty(trackStaffUserLoginName)) {
				if (mainUser == null) {
					return "修改失败:用户不存在" + loginName;
				}

			}
		} else if ("1".equals(type.trim())) {
			if (mainUser == null) {
				return "修改失败:用户不存在" + loginName;
			}
			omOrderTrack.setTrackStaffId(mainUser.getId());
			omOrderTrack.setTrackStaffName(loginName.trim());
		}
		omOrderTrackDao.update(omOrderTrack);
		return "修改成功";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId,
			HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<MainUser> list = UserUtils.getAllUser();
		// List<ProProduct> list = proProductService.findList(new ProProduct());
		for (int i = 0; i < list.size(); i++) {
			MainUser e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()))) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("name", e.getLoginName());
				mapList.add(map);
			}
		}
		return mapList;
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeOrderData")
	public List<Map<String, Object>> treeOrderData(@RequestParam(required = false) String extId,
			HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<UserOrder> list = userOrderService.findList(new UserOrder());
		for (int i = 0; i < list.size(); i++) {
			UserOrder e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()))) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getOrderCode());
				map.put("name", e.getOrderCode());
				map.put("orderCode", e.getOrderCode());
				mapList.add(map);
			}
		}
		return mapList;
	}

	/**
	 * 提现列表
	 * @param
	 * @param model
	 * @param query
	 * @return
	 */
	@RequestMapping(value = "listWithdraw")
	public String listByWithdraw(HttpServletRequest request, HttpServletResponse response, Model model, WithdrawQuery query) throws Exception{
		Page<UserWithdraw> page = withdrawService.listAllWithdraw(new Page<UserWithdraw>(request, response), query);
		model.addAttribute("page", page);
		model.addAttribute("query", query);
		return "modules/order/withdraw/withdrawList";
	}

	/**
	 * 提现详情页
	 * @param model
	 * @param transactionId 交流流水id
	 * @return
	 */
	@RequestMapping(value = "withdrawDetail")
	public String WithdrawDetail(Model model, String transactionId) throws Exception{
		UserWithdraw userWithdraw = withdrawService.getUserWithdrawByTransactionId(transactionId);
		userWithdraw.setTransaction(System.currentTimeMillis() + "");
		model.addAttribute("userWithdraw", userWithdraw);
		return "modules/order/withdraw/withdrawDetail";
	}

	/**
	 * 打款结果处理
	 * @param transactionId
	 * @param status
	 * @param userId
	 * @param money
	 * @param nickname
	 * @param type 1 打印 2 处理
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "handleWithdraw",method = RequestMethod.POST)
	public String HandleWithdraw(String transactionId, String status, String userId,Double money,String nickname,String type) throws Exception {
		if ("2".equals(type)) {
			withdrawService.handleWithdraw(transactionId, status, userId, money,nickname);
		} else if ("1".equals(type)) {
			UserWithdraw userWithdrawByTransactionId = withdrawService.getUserWithdrawByTransactionId(transactionId);
			withdrawService.handlePrint(userWithdrawByTransactionId);
		}
		return "redirect:" + Global.getAdminPath() + "/order/userOrder/listWithdraw";
	}
	/**
	 *打款结果处
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "handlePrint",method = RequestMethod.POST)
	public String handlePrint(UserWithdraw userWithdraw) throws Exception {
		withdrawService.handlePrint(userWithdraw);
		return "redirect:" + Global.getAdminPath() + "/order/userOrder/listWithdraw";
	}

	/**
	 * 操作查询列表
	 * @param request
	 * @param response
	 * @param model
	 * @param query
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "listHandle")
	public String listHandle(HttpServletRequest request, HttpServletResponse response, Model model, WithdrawQuery query) throws Exception{
		query.setStatus("");//默认查询所有
		Page<UserWithdraw> page = withdrawService.listHandle(new Page<UserWithdraw>(request, response), query);
		model.addAttribute("page", page);
		model.addAttribute("query", query);
		return "modules/order/withdraw/handleList";
	}
}